"use client";
import React, { useRef, useState } from "react";
import Chat, { useMessages } from "@chatui/core";
import "@chatui/core/dist/index.css";
import { Bubble } from "@ant-design/x";
import type { BubbleProps } from "@ant-design/x";
import { getAiByUsingGet } from "@/api/WishController";
import markdownit from "markdown-it";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";
import { ComposerHandle } from "@chatui/core/lib/components/Composer";
import { Icon } from "@chatui/core";
// 生成唯一ID的工具函数
const generateId = () =>
  Date.now().toString(36) + Math.random().toString(36).substr(2, 9);
const initialMessages = [
  {
    type: "system",
    content: { text: "" },
    _id: generateId(),
  },
  {
    type: "text",
    content: { text: "Hi，我是你的专属智能助理小蜜，有问题请随时找我哦~" },
    user: {
      avatar: "../assets/logo.png",
    },
    _id: generateId(),
  },
];

const md = markdownit({
  html: true,
  breaks: false,
  linkify: true,
});

const defaultQuickReplies = [
  { name: "java怎么学", isHighlight: false },
  { name: "前端怎么学", isHighlight: false },
  { name: "我的上一个问题是什么", isHighlight: false },
  { name: "清空", isHighlight: false },
];

export default function AiPage() {
  const loginUser = useSelector((state: RootState) => state.loginUser);
  const { messages, appendMsg, updateMsg } = useMessages(initialMessages);
  const [loadingId, setLoadingId] = useState<string | null>(null);
  const [quickReplies, setQuickReplies] = useState(defaultQuickReplies);
  const composerRef = useRef<ComposerHandle | null>(null);
  // 修改后的快速回复点击处理
  const handleQuickReplyClick = (item: { name: string }) => {
    if (item.name === "清空") {
      // 清空输入框内容
      if (composerRef.current) {
        composerRef.current.setText("");
      }
      // 取消所有高亮
      setQuickReplies((prev) =>
        prev.map((reply) => ({
          ...reply,
          isHighlight: false,
        })),
      );
      return;
    }
    // 更新高亮状态
    const updatedReplies = quickReplies.map((reply) => ({
      ...reply,
      isHighlight: reply.name === item.name,
    }));
    setQuickReplies(updatedReplies);
    // 发送消息
    handleSend("text", item.name);
  };

  const fetchAIResponse = async (question: string) => {
    try {
      const res = await getAiByUsingGet({ question });
      // @ts-ignore
      return res.data?.choices?.[0]?.message?.content;
    } catch (error) {
      console.error("API请求失败:", error);
      throw error;
    }
  };
  const userAvatars = {
    assistant: "../assets/logo.png",
    user: loginUser.userAvatar
      ? loginUser.userAvatar
      : "https://gw.alicdn.com/imgextra/i2/O1CN01fPEB9P1ylYWgaDuVR_!!6000000006619-0-tps-132-132.jpg",
  };

  const handleSend = async (type: string, val: string) => {
    if (type !== "text" || !val.trim()) return;

    // 用户消息
    const userMsg = {
      _id: generateId(),
      type: "text",
      content: { text: val },
      position: "right" as const,
      user: { avatar: userAvatars.user },
    };
    appendMsg(userMsg);

    // AI消息占位
    const aiMsgId = generateId();
    setLoadingId(aiMsgId);
    const placeholderMsg = {
      _id: aiMsgId,
      type: "text",
      content: { text: "正在思考..." },
      user: { avatar: userAvatars.assistant },
    };
    appendMsg(placeholderMsg);

    try {
      const aiResponse = await fetchAIResponse(val);

      // 更新占位消息
      updateMsg(aiMsgId, {
        ...placeholderMsg,
        content: { text: aiResponse || "收到，正在处理..." },
      });
    } catch (error) {
      updateMsg(aiMsgId, {
        ...placeholderMsg,
        content: { text: "请求失败，请稍后再试" },
      });
    } finally {
      setLoadingId(null);
    }
  };

  const renderMarkdown: BubbleProps["messageRender"] = (content) => (
    <div dangerouslySetInnerHTML={{ __html: md.render(content.trim()) }} />
  );

  const renderMessageContent = (msg: any) => {
    const { type, content, _id } = msg;
    if (type !== "text") return null;

    return (
      <Bubble
        typing
        loading={loadingId === _id}
        content={content.text}
        messageRender={renderMarkdown}
        styles={{
          content: {
            backgroundColor: msg.position === "right" ? "#e6f7ff" : "#fff",
            padding: "10px 15px",
            borderRadius: "12px",
          },
        }}
      />
    );
  };

  return (
    <div
      style={{
        width: "75%",
        margin: "0 auto",
        minHeight: "85vh",
        backgroundColor: "white",
        borderRadius: "8px",
        overflow: "hidden",
        boxShadow: "0 2px 10px rgba(0,0,0,0.1)",
      }}
    >
      <Chat
        navbar={{ title: "智能助理" }}
        messages={messages}
        renderMessageContent={renderMessageContent}
        quickReplies={quickReplies}
        onQuickReplyClick={handleQuickReplyClick}
        onSend={handleSend}
        composerRef={composerRef}
      />
    </div>
  );
}
